<!--
 * @Description: 描述
 * @Author: liym
 * @Date: 2025-05-08 20:14:38
 * @LastEditors: liym
 * @LastEditTime: 2025-06-06 17:12:37
-->
<template>
  <view class="order-list">
    <!-- 新增按钮和搜索框容器 -->
    <view class="button-search-container">
      <button @click="showAddModal" size="mini">新增订单</button>
      <!-- <uni-search-bar @confirm="searchOrders" :focus="true" 
          placeholder="输入订单ID搜索" 
          @cancel="handleSearchCancel" @clear="handleSearchClear">
        </uni-search-bar> -->

      <view class="uni-list">
        <view class="uni-list-cell">
          <!-- <view class="uni-list-cell-left">
            当前选择
          </view> -->
          <view class="uni-list-cell-db">
            <picker
              @change="bindPickerChange"
              range-key="userName"
              :range="agents"
            >
              <input
                class="uni-input"
                readonly
                v-model="searchName"
                placeholder="请选择代理商"
              />
            </picker>
          </view>
          <view
            v-if="searchName"
            class="search-clear"
            @click.stop="handleSearchClear"
            >清空</view
          >
        </view>
      </view>
    </view>

    <!-- 订单表格 -->
    <view class="table-container">
      <uni-table>
        <uni-tr>
          <uni-th align="center">订单ID</uni-th>
          <uni-th align="center">金额</uni-th>
          <uni-th align="center">时间</uni-th>
          <uni-th align="center">代理人</uni-th>
          <uni-th align="center">操作</uni-th>
        </uni-tr>
        <uni-tr v-for="order in orders" :key="order.id">
          <uni-td align="center">{{ order.id }}</uni-td>
          <uni-td align="center">{{ order.amount }} 元</uni-td>
          <uni-td align="center">{{ order.orderTime | formatDate }}</uni-td>
          <uni-td align="center">{{ order.agentId }}</uni-td>
          <uni-td align="center">
            <button size="mini" @click="showEditModal(order)">编辑</button>
            <button size="mini" @click="deleteOrder(order.id)">删除</button>
          </uni-td>
        </uni-tr>
      </uni-table>
    </view>
    <!-- 分页组件 -->
    <uni-pagination :total="total" :current="page" @change="handlePageChange" />
  </view>
</template>

<script>
import { adminRedirectionMixin } from '@/common/commonMixins.js'
import {
  getOrdersApi,
  updateOrderApi,
  addOrderApi,
  deleteOrderApi,
  getAgentsApi,
} from '@/api'
export default {
  mixins: [adminRedirectionMixin],
  data() {
    return {
      agents: [],
      agentIndex: null,
      orders: [],
      total: 0,
      page: 1,
      addModalVisible: false,
      editModalVisible: false,
      newOrder: {
        id: '',
        amount: '',
        createTime: '',
        agentName: '',
      },
      editedOrder: {
        id: '',
        amount: '',
        createTime: '',
        agentName: '',
      },
    }
  },
  filters: {
    formatDate: (date, format = 'yyyy-MM-dd HH:mm:ss') => {
      if (!(date instanceof Date)) {
        date = new Date(date) // 支持时间戳或字符串
      }

      const pad = (n) => n.toString().padStart(2, '0')

      const map = {
        yyyy: date.getFullYear(),
        MM: pad(date.getMonth() + 1),
        dd: pad(date.getDate()),
        HH: pad(date.getHours()),
        mm: pad(date.getMinutes()),
        ss: pad(date.getSeconds()),
      }

      return format.replace(/yyyy|MM|dd|HH|mm|ss/g, (match) => map[match])
    },
  },
  computed: {
    searchValue() {
      if (this.agentIndex !== null) {
        return this.agents[this.agentIndex].id
      }
      return null
    },
    searchName: {
      get() {
        if (this.agentIndex !== null) {
          return this.agents[this.agentIndex].userName
        }
        return ''
      },
      set(value) {
        console.log('value')
      },
    },
  },
  methods: {
    // // 搜索订单
    // searchOrders(keyword) {
    //   // 这里添加搜索订单的逻辑，例如向后端发送请求
    //   this.searchValue = keyword.value
    //   console.log('搜索订单', keyword);
    //   this.getList()
    // },
    handleSearchCancel() {},
    handleSearchClear() {
      console.log('ddddd')
      this.agentIndex = null

      this.$nextTick(() => {
        this.getList()
      })
    },
    // 删除订单
    async deleteOrder(orderId) {
      // 这里添加删除订单的逻辑，例如向后端发送请求
      // this.orders = this.orders.filter(order => order.id!== id);
      // console.log('删除订单:', id);
      try {
        uni.showLoading({
          title: 'loading',
          mask: true,
        })
        await deleteOrderApi(orderId)
        uni.hideLoading()
        this.getList()
      } catch {
        uni.hideLoading()
      }
    },
    // 处理分页变化
    handlePageChange(newPage) {
      this.page = newPage.current
      this.getList()
      // 这里添加处理分页变化的逻辑，例如向后端发送请求获取新数据
      console.log('切换到第', newPage.current, '页')
    },
    // 显示新增订单模态框
    showAddModal() {
      // this.addModalVisible = true;
      // this.newOrder = {
      //   id: '',
      //   amount: '',
      //   createTime: '',
      //   agentName: ''
      // };
      uni.setStorageSync('order', null)
      uni.navigateTo({
        url: '/pages/admin/orderInfo',
      })
    },
    // 新增订单
    addOrder() {
      // this.orders.push({ ...this.newOrder });
      // this.addModalVisible = true;
      // console.log('新增订单:', this.newOrder);
      this.setStorageSync('order', null)
      uni.navigateTo({
        url: `/pages/admin/orderInfo`,
      })
    },
    // 显示编辑订单模态框
    showEditModal(order) {
      // this.editModalVisible = true;
      // this.editedOrder = { ...order };

      uni.setStorageSync('order', order)
      uni.navigateTo({
        url: `/pages/admin/orderInfo?orderId=${order.id}`,
      })
    },
    // 更新订单
    updateOrder() {
      const index = this.orders.findIndex(
        (order) => order.id === this.editedOrder.id
      )
      if (index !== -1) {
        this.orders[index] = { ...this.editedOrder }
      }
      this.editModalVisible = false
      console.log('更新订单:', this.editedOrder)
    },
    async getList() {
      uni.showLoading({
        title: 'loading',
        mask: true,
      })
      try {
        const { data } = await getOrdersApi({
          currentPage: this.page,
          agentId: this.searchValue,
          pageSize: 10,
        })

        this.orders = data.records || []
        this.total = data.total
      } finally {
        uni.hideLoading()
      }
    },
    async getAgentList() {
      uni.showLoading({
        title: 'loading',
        mask: true,
      })
      try {
        const { data } = await getAgentsApi({
          currentPage: this.page,
          pageSize: 99999,
        })

        this.agents = data.records || []
      } finally {
        uni.hideLoading()
      }
    },
    bindPickerChange(event) {
      console.log(event.detail.value)
      this.agentIndex = event.detail.value

      this.$nextTick(() => {
        this.getList()
      })
    },
  },
  mounted() {
    this.getAgentList()
    this.getList()
  },
}
</script>

<style scoped>
.order-list {
  display: flex;
  flex-direction: column;
  padding: 10px;
  box-sizing: border-box;
  width: 100%;
}

.button-search-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
  .uni-list {
    flex: 1;
    min-width: 0;
  }
}

.button-search-container button {
  min-width: 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-right: 10px;
  margin-bottom: 0;
  flex-basis: auto;
  flex-grow: 0;
  flex-shrink: 1;
  height: auto;
  padding: 5px 10px;
}

uni-search-bar {
  flex: 1;
}

.table-container {
  width: 100%;
  overflow-x: auto;
}

uni-pagination {
  margin-top: 10px;
}

.search-clear {
  padding: 0 10px;
  color: #2979ff;
}
</style>
